package com.gz.servlet.httpservletrequest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/requestServlet")
public class HttpServletRequestMethods extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求头内容
        System.out.println("请求的资源路径URI= " + request.getRequestURI());
        System.out.println("请求的统一资源路径(绝对路径)URL= " + request.getRequestURL());
        System.out.println("请求的客户端ip地址= " + request.getRemoteAddr());
        System.out.println("http请求头HOST="+request.getHeader("Host"));

        //可以用作防盗帘
        //比如从register点击注册重定向，这里返回的就是register的地址
        System.out.println("该请求发起的地址是: "+request.getHeader("referer"));
        //获取用户用的什么浏览器
        String header = request.getHeader("User-Agent");
        String[] s = header.split(" ");
        //得到Edg/133.0.0.0
        String s1 = s[s.length - 1].split("\\/")[0];//得到Edg
        System.out.println("浏览器= " + s1);
        //如果有让你调查用户访问你的网站都用什么浏览器，可以这样获得

        System.out.println("http请求方式: "+request.getMethod());

        //获取表单的数据(单个数据)
        request.setCharacterEncoding("UTF-8");//可以解决接收中文参数乱码的问题，
                                                // 如账号输入中文不写这个会乱码
        //注意与response解决发送数据给浏览器的中文乱码的方法区别:
        //1.response的response.setContentType("text/html;charset=utf-8");
        //用来让自己写的页面html呈现出来不乱码
        //2.request的request.setCharacterEncoding("UTF-8");
        //用来解决页面传递参数，然后我来获取参数时得到的不是乱码信息

        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println("username= " + username);
        System.out.println("pwd= " + password);
        //快捷键iter 加强for循环
        for (String hobby : hobbies) {
            System.out.println("hobby= " + hobby);//会自动获取勾选的
        }

        //返回给浏览器获取到的数据
        //text/html即mine类型，可以是其他的，比如返回纯文本(即把<h1>这种字也返回)text/plain、文件等等
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("提取到的数据: <br> username= "+ username+"<br>");
        writer.println("pwd= " + password+"<br>");
        for (String hobby : hobbies) {
            writer.println("hobby= " + hobby+"<br>");//会自动获取勾选的
        }
    }
}
